<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          go微服务demo - Congz Blog
        
    </title>

    <link rel="canonical" href="http://congz.top/2020/09/15/go微服务demo/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('background.jpg')
            /*post*/
        
    }
    
    #signature{
        background-image: url('/null');
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#go-micro" title="go-micro">go-micro</a>
                            
                              <a class="tag" href="/tags/#微服务" title="微服务">微服务</a>
                            
                        </div>
                        <h1>go微服务demo</h1>
                        <h2 class="subheading"></h2>
                        <span class="meta">
                            Posted by Congz on
                            2020-09-15
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Congz</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/about/">About</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/archive/">Archives</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/tags/">Tags</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <h1><span id="go-微服务-demo">go 微服务 Demo</span></h1>
<h2><span id="demo-详情">Demo 详情</span></h2>
<p>本 Demo 以获取商品信息为例子</p>
<p>分为 Server 端和 Client 端</p>
<p>Server 端使用 go-micro 实现简单业务逻辑</p>
<p>Client 端使用 rpc 调用 Server 端的处理函数并使用 gin 向外暴露 HTTP 接口</p>
<h3><span id="demo-依赖">Demo 依赖</span></h3>
<ul>
<li>gin</li>
<li>go-micro</li>
<li>protobuf</li>
<li>consul</li>
<li>docker</li>
<li>protoc-go-inject-tag</li>
<li>protoc-gen-go</li>
</ul>
<h2><span id="docker-容器启动-consul">Docker 容器启动 consul</span></h2>
<p>终端输入</p>
<p><code>docker run -p 8500:8500/tcp consul agent -server -ui -bootstrap-expect=1 -client=0.0.0.0</code></p>
<p>-server consul 支持以 server 或 client 的模式运行, server 是服务发现模块的核心, client 主要用于转发请求</p>
<p>-bootstrap-expect 指定 consul 将等待几个节点连通，成为一个完整的集群</p>
<p>-client 0.0.0.0 表示任何地址可以访问。</p>
<p>-ui 提供图形化的界面。</p>
<p>更多参数请查阅相关文档</p>
<p>浏览器访问 <code>localhost:8500</code>可以看到 consul 的图形化界面</p>
<h2><span id="server-端-demo">Server 端 Demo</span></h2>
<h3><span id="目录结构">目录结构</span></h3>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">go-micro-grpc/</span><br><span class="line">├── serviceImpl</span><br><span class="line">│	├── productService.go</span><br><span class="line">├── services</span><br><span class="line">│	├── protos</span><br><span class="line">│	│	├── models.proto</span><br><span class="line">│	│	├── productService.proto</span><br><span class="line">│   ├── models<span class="selector-class">.pb</span>.go</span><br><span class="line">│   ├── productService<span class="selector-class">.pb</span>.go</span><br><span class="line">│   ├── productService<span class="selector-class">.pb</span><span class="selector-class">.micro</span>.go</span><br><span class="line">├── go.mod</span><br><span class="line">├── go.sum</span><br><span class="line">├── main.go</span><br></pre></td></tr></table></figure>
<ul>
<li>serviceImpl：业务逻辑实现</li>
<li>services：proto 文件及生成文件</li>
</ul>
<h3><span id="proto-编写及自动生成-pbgo">proto 编写及自动生成 pb.go</span></h3>
<p>models.proto</p>
<figure class="highlight protobuf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">syntax=<span class="string">"proto3"</span>;</span><br><span class="line"><span class="keyword">package</span> services;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">message</span> <span class="title">ProductModel</span></span>&#123;</span><br><span class="line">  <span class="comment">// @inject_tag: json:"product_id"</span></span><br><span class="line">  <span class="built_in">int32</span> ProductID=<span class="number">1</span>;</span><br><span class="line">  <span class="comment">// @inject_tag: json:"product_name"</span></span><br><span class="line">  <span class="built_in">string</span> ProductName=<span class="number">2</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>productService.proto</p>
<figure class="highlight protobuf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">syntax=<span class="string">"proto3"</span>;</span><br><span class="line"><span class="keyword">package</span> services;</span><br><span class="line"><span class="keyword">import</span> <span class="string">"models.proto"</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">message</span> <span class="title">ProductRequest</span></span>&#123;</span><br><span class="line">  <span class="comment">// @inject_tag: json:"size" form:"size"</span></span><br><span class="line">  <span class="built_in">int32</span> size=<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">message</span> <span class="title">ProductListResponse</span></span>&#123;</span><br><span class="line">  <span class="keyword">repeated</span> ProductModel ProductList=<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">service</span> <span class="title">ProductService</span></span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">rpc</span> GetProductsList(ProductRequest) <span class="keyword">returns</span>(ProductListResponse)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>进入 proto 文件的路径，终端输入</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">生成pb.go文件</span></span><br><span class="line">protoc  --go_out=../ models.proto</span><br><span class="line"><span class="meta">#</span><span class="bash">生成pb.go和pb.micro.go文件</span></span><br><span class="line">protoc --micro_out=../ --go_out=../ productService.proto</span><br><span class="line"><span class="meta">#</span><span class="bash">在pb.go文件生成结构体验证标记</span></span><br><span class="line">protoc-go-inject-tag -input=../models.pb.go</span><br><span class="line">protoc-go-inject-tag -input=../productService.pb.go</span><br></pre></td></tr></table></figure>
<p>执行完毕后，上一级目录会生成<code>models.pb.go、productService.pb.go、productService.pb.micro.go</code>三个文件</p>
<h3><span id="maingo">main.go</span></h3>
<p>将服务注册到 consul</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"go-micro-grpc/serviceImpl"</span></span><br><span class="line">	<span class="string">"go-micro-grpc/services"</span></span><br><span class="line"></span><br><span class="line">	<span class="string">"github.com/micro/go-micro"</span></span><br><span class="line">	<span class="string">"github.com/micro/go-micro/registry"</span></span><br><span class="line">	<span class="string">"github.com/micro/go-plugins/registry/consul"</span></span><br><span class="line"></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">//consul注册件</span></span><br><span class="line">	consulReg := consul.NewRegistry(</span><br><span class="line">		registry.Addrs(<span class="string">"localhost:8500"</span>),</span><br><span class="line">	)</span><br><span class="line">	<span class="comment">//创建微服务实例，并注册到consul</span></span><br><span class="line">	microService := micro.NewService(</span><br><span class="line">		micro.Name(<span class="string">"grpcProductService"</span>),</span><br><span class="line">		micro.Address(<span class="string">":8080"</span>),</span><br><span class="line">		micro.Registry(consulReg),</span><br><span class="line">	)</span><br><span class="line">	<span class="comment">//接收命令行参数 如--server_address</span></span><br><span class="line">	microService.Init()</span><br><span class="line"></span><br><span class="line">	<span class="comment">//注册商品服务</span></span><br><span class="line">	services.RegisterProductServiceHandler(microService.Server(), <span class="built_in">new</span>(serviceImpl.ProductService))</span><br><span class="line">	microService.Run()</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3><span id="serviceimplproductservicego">serviceImpl/productService.go</span></h3>
<p>简单的业务逻辑</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> serviceImpl</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"context"</span></span><br><span class="line">	<span class="string">"go-micro-grpc/services"</span></span><br><span class="line">	<span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">NewProduct</span><span class="params">(id <span class="keyword">int32</span>, name <span class="keyword">string</span>)</span> *<span class="title">services</span>.<span class="title">ProductModel</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;services.ProductModel&#123;ProductID: id, ProductName: name&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> ProductService <span class="keyword">struct</span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//实现商品服务接口</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(*ProductService)</span> <span class="title">GetProductsList</span><span class="params">(ctx context.Context, in *services.ProductRequest, res *services.ProductListResponse)</span> <span class="title">error</span></span> &#123;</span><br><span class="line">	productList := <span class="built_in">make</span>([]*services.ProductModel, <span class="number">0</span>)</span><br><span class="line">	<span class="keyword">var</span> i <span class="keyword">int32</span></span><br><span class="line">	<span class="keyword">for</span> i = <span class="number">0</span>; i &lt; in.Size; i++ &#123;</span><br><span class="line">		productList = <span class="built_in">append</span>(productList, NewProduct(i, <span class="string">"ProductService"</span>+strconv.Itoa(<span class="number">100</span>+<span class="keyword">int</span>(i))))</span><br><span class="line">	&#125;</span><br><span class="line">	res.ProductList = productList</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2><span id="client-端-demo">Client 端 Demo</span></h2>
<h3><span id="目录结构">目录结构</span></h3>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">go-micro-ginClient/</span><br><span class="line">├── services</span><br><span class="line">│	├── protos</span><br><span class="line">│	│	├── models.proto</span><br><span class="line">│	│	├── productService.proto</span><br><span class="line">│   ├── models<span class="selector-class">.pb</span>.go</span><br><span class="line">│   ├── productService<span class="selector-class">.pb</span>.go</span><br><span class="line">│   ├── productService<span class="selector-class">.pb</span><span class="selector-class">.micro</span>.go</span><br><span class="line">├── webLib</span><br><span class="line">│	├── handlers.go</span><br><span class="line">│	├── middlewares.go</span><br><span class="line">│	├── router.go</span><br><span class="line">├── go.mod</span><br><span class="line">├── go.sum</span><br><span class="line">├── main.go</span><br></pre></td></tr></table></figure>
<ul>
<li>services：proto 文件及生成文件</li>
<li>webLib：gin 路由和处理函数封装</li>
</ul>
<h3><span id="proto-编写及自动生成-pbgo">proto 编写及自动生成 pb.go</span></h3>
<p>具体操作和前面 server 端一样</p>
<h3><span id="maingo">main.go</span></h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"go-micro-ginClient/services"</span></span><br><span class="line">	<span class="string">"go-micro-ginClient/webLib"</span></span><br><span class="line"></span><br><span class="line">	<span class="string">"github.com/micro/go-micro"</span></span><br><span class="line">	<span class="string">"github.com/micro/go-micro/registry"</span></span><br><span class="line">	<span class="string">"github.com/micro/go-micro/web"</span></span><br><span class="line">	<span class="string">"github.com/micro/go-plugins/registry/consul"</span></span><br><span class="line"></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">//consul注册件</span></span><br><span class="line">	consulReq := consul.NewRegistry(</span><br><span class="line">		registry.Addrs(<span class="string">"localhost:8500"</span>),</span><br><span class="line">	)</span><br><span class="line"></span><br><span class="line">	myService := micro.NewService(micro.Name(<span class="string">"productService.client"</span>))</span><br><span class="line">	<span class="comment">//服务调用实例</span></span><br><span class="line">	productService := services.NewProductService(<span class="string">"grpcProductService"</span>, myService.Client())</span><br><span class="line"></span><br><span class="line">	<span class="comment">//创建微服务实例，使用gin暴露http接口并注册到consul</span></span><br><span class="line">	server := web.NewService(</span><br><span class="line">		web.Name(<span class="string">"httpProductService"</span>),</span><br><span class="line">		web.Address(<span class="string">":8000"</span>),</span><br><span class="line">		<span class="comment">//将服务调用实例使用gin处理</span></span><br><span class="line">		web.Handler(webLib.NewRouter(productService)),</span><br><span class="line">		web.Registry(consulReq),</span><br><span class="line">	)</span><br><span class="line">	<span class="comment">//接收命令行参数</span></span><br><span class="line">	server.Init()</span><br><span class="line">	server.Run()</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3><span id="weblibroutergo">webLib/router.go</span></h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> webLib</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"go-micro-ginClient/services"</span></span><br><span class="line"></span><br><span class="line">	<span class="string">"github.com/gin-gonic/gin"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">//接收服务调用实例的参数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">NewRouter</span><span class="params">(productService services.ProductService)</span> *<span class="title">gin</span>.<span class="title">Engine</span></span> &#123;</span><br><span class="line">	ginRouter := gin.Default()</span><br><span class="line">	<span class="comment">//使用中间件，接收服务调用实例</span></span><br><span class="line">	ginRouter.Use(InitMiddleware(productService))</span><br><span class="line">	<span class="comment">//向外暴露http接口，本Demo使用Post请求</span></span><br><span class="line">	v1 := ginRouter.Group(<span class="string">"/api/v1"</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		v1.POST(<span class="string">"/products"</span>, GetProductsList)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> ginRouter</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3><span id="weblibmiddlewaresgo">webLib/middlewares.go</span></h3>
<p>gin 的中间件</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> webLib</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"go-micro-ginClient/services"</span></span><br><span class="line"></span><br><span class="line">	<span class="string">"github.com/gin-gonic/gin"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">InitMiddleware</span><span class="params">(productService services.ProductService)</span> <span class="title">gin</span>.<span class="title">HandlerFunc</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(context *gin.Context)</span></span> &#123;</span><br><span class="line">		<span class="comment">//将实例存到context.Keys里</span></span><br><span class="line">		context.Keys = <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="keyword">string</span>]<span class="keyword">interface</span>&#123;&#125;)</span><br><span class="line">		context.Keys[<span class="string">"productService"</span>] = productService</span><br><span class="line">		context.Next()</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3><span id="weblibhandlersgo">webLib/handlers.go</span></h3>
<p>封装调用函数</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> webLib</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"context"</span></span><br><span class="line">	<span class="string">"go-micro-ginClient/services"</span></span><br><span class="line"></span><br><span class="line">	<span class="string">"github.com/gin-gonic/gin"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用rpc调用服务端的处理函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GetProductsList</span><span class="params">(ginCtx *gin.Context)</span></span> &#123;</span><br><span class="line">	productService := ginCtx.Keys[<span class="string">"productService"</span>].(services.ProductService)</span><br><span class="line">	<span class="keyword">var</span> productReq services.ProductRequest</span><br><span class="line">	<span class="comment">//解析请求</span></span><br><span class="line">	err := ginCtx.Bind(&amp;productReq)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		ginCtx.JSON(<span class="number">500</span>, gin.H&#123;<span class="string">"status"</span>: err.Error()&#125;)</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="comment">//调用服务端的函数</span></span><br><span class="line">		productRes, _ := productService.GetProductsList(context.Background(), &amp;productReq)</span><br><span class="line">		ginCtx.JSON(<span class="number">200</span>, gin.H&#123;<span class="string">"data"</span>: productRes.ProductList&#125;)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2><span id="postman-测试接口">Postman 测试接口</span></h2>
<p>POST 请求访问 <code>localhost:8000/api/v1/products</code> 并带 form 或 json 参数<code>&quot;size&quot;:1</code>，请求成功会得到商品信息</p>

                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/2020/09/16/go-micro使用熔断器中间件/" data-toggle="tooltip" data-placement="top" title="go-micro 使用熔断器中间件">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/2020/09/01/grpc流模式demo/" data-toggle="tooltip" data-placement="top" title="grpc 流模式 demo">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                
                <!-- disqus comment end -->
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">Contents</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">go 微服务 Demo</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">Demo 详情</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.1.1.</span> <span class="toc-nav-text">Demo 依赖</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">Docker 容器启动 consul</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.3.</span> <span class="toc-nav-text">Server 端 Demo</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.3.1.</span> <span class="toc-nav-text">目录结构</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.3.2.</span> <span class="toc-nav-text">proto 编写及自动生成 pb.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.3.3.</span> <span class="toc-nav-text">main.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.3.4.</span> <span class="toc-nav-text">serviceImpl/productService.go</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.</span> <span class="toc-nav-text">Client 端 Demo</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.1.</span> <span class="toc-nav-text">目录结构</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.2.</span> <span class="toc-nav-text">proto 编写及自动生成 pb.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.3.</span> <span class="toc-nav-text">main.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.4.</span> <span class="toc-nav-text">webLib/router.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.5.</span> <span class="toc-nav-text">webLib/middlewares.go</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.4.6.</span> <span class="toc-nav-text">webLib/handlers.go</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.5.</span> <span class="toc-nav-text">Postman 测试接口</span></a></li></ol></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#go-micro" title="go-micro">go-micro</a>
                        
                          <a class="tag" href="/tags/#微服务" title="微服务">微服务</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="https://blog.csdn.net/Congzzzzz" target="_blank">CSDN blog Congz</a></li>
                    
                        <li><a href="https://gitee.com/congz666" target="_blank">Gitee Congz</a></li>
                    
                        <li><a href="http://cmall.congz.top/#/" target="_blank">CMall</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>




<!-- disqus embedded js code start (one page only need to embed once) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "your-disqus-ID";
    var disqus_identifier = "http://congz.top/2020/09/15/go微服务demo/";
    var disqus_url = "http://congz.top/2020/09/15/go微服务demo/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus embedded js code start end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: 'ℬ'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
               
          <li>
            <a
              target="_blank"
              href="https://github.com/congz666"
            >
              <span class="fa-stack fa-lg">
                <i class="fa fa-circle fa-stack-2x"></i>
                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
              </span>
            </a>
          </li>
           
        </ul>
        <p class="copyright text-muted">
          Copyright &copy; Congz 2021
          <br />
          Theme by <a href="http://huangxuan.me">Hux</a>
          <span style="display: inline-block; margin: 0 5px">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by <a href="http://congz.top">Congz</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>

<!-- async load function -->
<script>
  function async(u, c) {
    var d = document,
      t = "script",
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener(
        "load",
        function (e) {
          c(null, e);
        },
        false
      );
    }
    s.parentNode.insertBefore(o, s);
  }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->

<!-- jquery.tagcloud.js -->
<script>
  // only load tagcloud.js in tag.html
  if ($("#tag_cloud").length !== 0) {
    async(
      "http://congz.top/js/jquery.tagcloud.js",
      function () {
        $.fn.tagcloud.defaults = {
          //size: {start: 1, end: 1, unit: 'em'},
          color: { start: "#bbbbee", end: "#0085a1" },
        };
        $("#tag_cloud a").tagcloud();
      }
    );
  }
</script>

<!--fastClick.js -->
<script>
  async(
    "https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js",
    function () {
      var $nav = document.querySelector("nav");
      if ($nav) FastClick.attach($nav);
    }
  );
</script>

<!-- Google Analytics -->


<script>
  // dynamic User by Hux
  var _gaId = "UA-XXXXXXXX-X";
  var _gaDomain = "congz";

  // Originial
  (function (i, s, o, g, r, a, m) {
    i["GoogleAnalyticsObject"] = r;
    (i[r] =
      i[r] ||
      function () {
        (i[r].q = i[r].q || []).push(arguments);
      }),
      (i[r].l = 1 * new Date());
    (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
  })(
    window,
    document,
    "script",
    "//www.google-analytics.com/analytics.js",
    "ga"
  );

  ga("create", _gaId, _gaDomain);
  ga("send", "pageview");
</script>



<!-- Baidu Tongji -->




	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="http://congz.top/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
